<template>
    <div class="addArehousing">
        <van-nav-bar title="新增出库" left-arrow @click-left="handleLeft">
        </van-nav-bar>
        <router-view />
        <div class="flexd">
            <div @click="selectOne()" class="addArehousing_item">
                <div class="imgs"><van-image :src="add"></van-image></div>
                <div class="title">选择商品</div>
            </div>
            <div @click="scanCode" class="addArehousing_item addArehousing_code">
                <div class="imgs"><van-image :src="saoma"></van-image></div>
                <div class="title">扫码出库</div>
            </div>
        </div>
        <div class="titles">商品明细</div>
        <div class="conent">
            <div v-for="(item, index) in outboundList" :key="index" class="conent_pre">
                <div class="conent_pre_header">
                    <div class="conent_pre_img">
                        <van-image :src="item.productImage + '?x-oss-process=image/resize,w_300'"
                            v-if="item.productImage" @click="enlargeImage(item.productImage)"></van-image>
                        <van-image :src="errImg" v-else></van-image>
                    </div>
                    <div class="conent_pre_des">
                        <div class="contnt_title">
                            <div class="contnt_styleName">
                                {{ item.styleName }}
                            </div>
                            <div class="contnt_status">
                                已上架
                            </div>
                        </div>
                        <div class="contnt_mechanism">
                            {{ item.sellingPoints }}
                        </div>
                        <div class="contnt_bottom">
                            <div class="price">￥ {{ item.mechanismList[0]?.price ||
                                item.mechanismList[0]?.costPrice
                                }}</div>
                            <div class="commission" v-if="item.mechanismList[0]?.commission">佣 {{
                                (item.mechanismList[0]?.commission || 0) + "%" }}</div>
                            <div class="coreName">{{ item.coreName }}</div>
                        </div>
                    </div>
                </div>
                <div class="product_detail_title--content">
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">规格/材质：</div>
                        <div class="product_detail_title-content-info-content">
                            {{ item.specs }}
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">出库数量：</div>
                        <div class="product_detail_title-content-info-content">
                            <van-stepper v-model="totalList[index]" :max="item.stockInfo?.stockAvailable" integer
                                :before-change="onChange" />
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">当前库存：</div>
                        <div class="contents" style="color: #0094FF;">
                            {{ item.stockInfo?.stockAvailable }}件
                        </div>
                        <div class="buttons" @click="removeClick(item)">移除</div>
                    </div>
                </div>
            </div>
        </div>
        <van-overlay :show="overlayShow">
            <van-loading color="#1989fa">加载中...</van-loading>
        </van-overlay>
        <van-dialog v-model:show="dialogShow" title="提示" :showConfirmButton="false">
            <div class="dialog_title">是否对所选商品进行出库？</div>
            <div class="dialog_buttons">
                <div @click="cancel" class="cancel">取消</div>
                <!-- <div @click="warehousingClick" class="save" v-throttle:click>确认</div> -->
                <van-button class="button" @click="warehousingClick" :loading="loading" loading-text="执行中..."
                    v-throttle:click>
                    确认
                </van-button>
            </div>
        </van-dialog>
        <div class="conputed_bottom" v-show="buttonsShow">
            <div class="retained">
                <div class="label">拍照留存</div>
                <div class="value">
                    <div v-for="(item, index) in outImageList" :key="index" class="imgList">
                        <div class="loading_pic" v-if="!item.url">
                            <van-loading type="spinner" size="20" />
                        </div>
                        <van-image v-if="item.url" :src="item.url ? item.url + '?x-oss-process=image/resize,w_300' : ''"
                            @click="enlargeImage(item.url)"></van-image>
                        <van-icon v-if="item.url" name="cross" color="#fff"
                            @click.prevent="deleteImg(outImageList, index)" />
                    </div>
                    <van-image :src="upload" v-if="outImageList.length < 5" @click="postImage('outImage', 5)"
                        v-throttle:click></van-image>
                </div>
            </div>
            <div class="conputed_bottom_total">
                <div class="conputed_bottom_left">
                    <van-image :src="ruku"></van-image>
                    共<span class="span">{{ total }}</span>件商品出库
                </div>
                <div class="button" @click="warehousingSave">出库</div>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import { getSupplierAddProductsById } from "@/api/productList/index";
import { showConfirmDialog, showFailToast, showImagePreview, showSuccessToast } from "vant";
import { computed, onMounted, ref, watch, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getEnvValue } from "@/utils/index";
import { addStockOut } from "@/api/productHome/index"
import { isPositiveInteger } from '@/utils/validate'
import { handleImageUpdate } from "@/utils/handleImageUpdate";
const loading = ref(false)
const router = useRouter();
const route = useRoute();
const errImg = new URL("@/assets/home/error.png", import.meta.url).href;
const saoma = new URL("@/assets/productHome/icon_saoyisao1.png", import.meta.url).href;
const add = new URL("@/assets/productHome/icon_tianjia.png", import.meta.url).href;
const ruku = new URL("@/assets/productHome/icon_ruku.png", import.meta.url).href;
const upload = new URL("@/assets/home/upload.png", import.meta.url).href;

const outboundList = ref<any>([])
const totalList = ref<any>([])
const overlayShow = ref(false)
// 留存
const outImageList = ref<any[]>([]);

// 二次确认弹窗
const dialogShow = ref(false)
const buttonsShow = ref(true)
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
// 在组件挂载完成后添加事件监听器
onMounted(() => {
    defaultPhoneHeight.value = window.innerHeight;
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
})
// 处理窗口大小变化的函数
const handleResize = () => {
    nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});
watch(nowPhoneHeight, () => {
    if (defaultPhoneHeight.value != nowPhoneHeight.value) {
        // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
        buttonsShow.value = false
    } else {
        // 相等代表软键盘收起后,与上同理
        buttonsShow.value = true
    }
})

// 入口 主播选品出库 == 1 退还供应商出库 == 2
const indexs = computed(() => {
    return route.query.index;
});

// 主播id
const coreId = computed(() => {
    return route.query.coreId;
});

// 关联库存单 数据留存
const info = computed(() => {
    return route.query.info;
})

/** 商品详情传过来的商品 */
const detailInfo = computed(() => {
    return route.query.detailInfo;
});

const total = computed(() => {
    return totalList.value.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
});

watch(
    () => detailInfo.value,
    (v: any) => {
        if (v) {
            const date = JSON.parse(v)
            if (date.productImage !== '') {
                date.productImage = getEnvValue("VITE_APP_PIC_URL") + date.productImage.split(',')[0]
            }
            outboundList.value.push(date)
            localStorage.setItem("outboundList", JSON.stringify(outboundList.value));
            localStorage.setItem('outboundsId', JSON.stringify([date.id]))
        }
    },
    { immediate: true }
)


watch(
    () => info.value,
    (v: any) => {
        // 选择出库商品时
        if (v) {
            if (localStorage.getItem('outboundList')) {
                outboundList.value = JSON.parse(localStorage.getItem('outboundList') as any)
                const date = JSON.parse(v)
                outboundList.value.unshift(...date)
            } else {
                const date = JSON.parse(v)
                outboundList.value.unshift(...date)
            }
            const total = JSON.parse(localStorage.getItem('totalList') as any)
            if (total && total.length > 0) {
                total.unshift(1)
            }
            totalList.value = total
            // 没有选择出库商品时
        } else {
            outboundList.value = JSON.parse(localStorage.getItem('outboundList') as any) || []
            totalList.value = JSON.parse(localStorage.getItem('totalList') as any) || []
        }
        // 拍照留存
        outImageList.value = JSON.parse(localStorage.getItem('outImageList') as any) || []
    },
    { immediate: true }
);

/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};

/** 选择商品 */
const selectOne = () => {
    localStorage.setItem("outboundList", JSON.stringify(outboundList.value));
    localStorage.setItem("totalList", JSON.stringify(totalList.value));
    localStorage.setItem("outImageList", JSON.stringify(outImageList.value));
    router.push({
        path: '/finishedGoods',
        query: {
            coreId: coreId.value,
            index: indexs.value,
        }
    })

}
/** 回退 */
const handleLeft = () => {
    if (outboundList.value.length) {
        showConfirmDialog({
            message:
                '退出后将不保留未完成操作',
        })
            .then(() => {
                router.push({
                    path: '/selectAnchor',
                    query: {
                        index: indexs.value
                    }
                })
                // 清除缓存
                localStorage.removeItem('outboundList')
                localStorage.removeItem('outboundsId')
                localStorage.removeItem('totalList')
                localStorage.removeItem('outImageList')
            })
            .catch(() => {
                // on cancel
            });
    } else {
        router.push({
            path: '/selectAnchor',
            query: {
                index: indexs.value
            }
        })
        // 清除缓存
        localStorage.removeItem('outboundList')
        localStorage.removeItem('outboundsId')
        localStorage.removeItem('totalList')
        localStorage.removeItem('outImageList')
    }
}
/** 移除当前数据 */
const removeClick = (item: any) => {
    const removeIndex = outboundList.value.indexOf(item)
    outboundList.value.splice(removeIndex, 1)
    totalList.value.splice(removeIndex, 1)
    if (localStorage.getItem('outboundsId')) {
        const arrList = JSON.parse(localStorage.getItem('outboundsId') as any)
        arrList.splice(removeIndex, 1)
        localStorage.setItem('outboundsId', JSON.stringify(arrList))
    }
}
/** 出库二次确认 */
const warehousingSave = () => {
    dialogShow.value = true
}
/** 出库二次取消 */
const cancel = () => {
    dialogShow.value = false
}
/** 出库 */
const warehousingClick = async () => {
    if (outboundList.value.length == 0) {
        showFailToast('请选择出库商品');
    } else {


        try {
            const businessList = outboundList.value.map((item: any, index: number) => {
                return {
                    productId: item.id,
                    outNum: totalList.value[index],
                    stockCode: item.stockCode,
                    stockNum: item.stockInfo?.stockAvailable,
                    outType: Number(indexs.value) + 1
                }
            })
            await addStockOut({
                businessList,
                coreUserId: coreId.value,
                outType: Number(indexs.value) + 1,
                // 拍照留存
                outImage: getPicByfullPath(outImageList.value)
            })
            showSuccessToast('商品出库成功')
            loading.value = false

            // 清除缓存
            localStorage.removeItem('outboundList')
            localStorage.removeItem('outboundsId')
            localStorage.removeItem('totalList')
            localStorage.removeItem('outImageList')

            router.push({
                path: '/addOutboundSuccess'
            })
        } catch (error) {
            if (error == 'timeout') {
                showFailToast('商品出库失败');
            }
            loading.value = false
        }
    }
}
/** 扫码出库 */
const scanCode = async () => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "scanCode",
            name: "scanOutbound"
        },
    });

}

// 步进器限制 阻止输入负数
const onChange = (value: string): any => {
    return new Promise((resolve) => {
        if (value !== '-') {
            resolve(true);
        }
    });
}
/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
/** uniapp端回传扫码数据 */
(window as any).msgFromUniapp = async (arg) => {
    // 货架
    if (arg.name == 'scanOutbound') {
        overlayShow.value = true
        try {
            if (isPositiveInteger(arg.productId)) {
                const res = await getSupplierAddProductsById({ productId: arg.productId });
                if (res.data.shelvesStatus == 2) {
                    if (res.data.stockInfo?.stockAvailable < 1) {
                        overlayShow.value = false
                        showFailToast('该商品库存数为' + res.data.stockInfo?.stockAvailable);
                    } else {
                        res.data.productImage = getEnvValue("VITE_APP_PIC_URL") + res.data.productImage.split(',')[0]
                        if (localStorage.getItem('outboundsId')) {
                            const arrList = JSON.parse(localStorage.getItem('outboundsId') as any)
                            // 出库商品id ==> 已经存在该商品id
                            if (arrList.indexOf(res.data.id) !== -1) {
                                const ind = arrList.indexOf(res.data.id)
                                if (totalList.value[ind] < res.data.stockInfo?.stockAvailable) {
                                    totalList.value[ind] = Number(totalList.value[ind]) + 1;
                                    localStorage.setItem("totalList", JSON.stringify(totalList.value));
                                }
                            } else {
                                outboundList.value.push(res.data)
                                localStorage.setItem("outboundList", JSON.stringify(outboundList.value));
                                arrList.push(res.data.id)
                                localStorage.setItem('outboundsId', JSON.stringify(arrList))
                            }

                        } else {
                            outboundList.value.push(res.data)
                            localStorage.setItem("outboundList", JSON.stringify(outboundList.value));
                            const idList = outboundList.value.map(item => item.id)
                            localStorage.setItem('outboundsId', JSON.stringify(idList))
                        }
                        overlayShow.value = false
                    }
                } else {
                    showFailToast({ message: '该商品未上架' });
                    overlayShow.value = false
                }
            } else {
                showFailToast({ message: '该商品不存在' });
                overlayShow.value = false
            }
        } catch (error) {
            overlayShow.value = false
        }
    }
    // 拍照留存
    if (arg.name == 'outImage') {
        const imageLists = {
            outImage: outImageList.value,
        };

        const maxCounts = {
            outImage: 5,
        };

        const imageList = imageLists[arg.name];
        const maxCount = maxCounts[arg.name];

        handleImageUpdate(imageList, arg, maxCount);
    }
}
/** 删除 */
const deleteImg = (list: any, index: number) => {
    list.splice(index, 1);
};
const store = loginStore();
const { token } = storeToRefs(store);
/** 上传图片 */
const postImage = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "img",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + "/resource/oss/upload",
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};
</script>

<style lang="less" scoped>
.addArehousing {
    height: calc(100vh - 44px);
    width: 100%;
    background: #F6FAFF;
    // padding-top: 15px;
    box-sizing: border-box;
    overflow: hidden;
    display: flex;
    flex-flow: column;

    :deep(.van-overlay) {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    :deep(.van-dialog__content) {
        box-sizing: border-box;
        padding: 20px;
    }

    .dialog_title {
        text-align: center;
        margin: 20px;
    }

    .dialog_buttons {
        .button {
            color: #FFFFFF;
            font-size: 14px;
            width: 137px;
            height: 44px;
            background: #0094FF;
            border-radius: 23px;
            margin: auto;
            display: flex;
            justify-content: center;
        }

        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .cancel {
            width: 135px;
            height: 44px;
            border-radius: 23px;
            border: 1px solid #1A1B1C;
            text-align: center;
            line-height: 44px;
        }

        .save {
            width: 135px;
            height: 44px;
            background: #0094FF;
            border-radius: 23px;
            text-align: center;
            line-height: 44px;
            font-weight: 400;
            font-size: 14px;
            color: #FFFFFF;
        }
    }

    .addArehousing_code {
        margin-top: 15px !important;
    }

    .addArehousing_item {
        width: 151px;
        height: 42px;
        background: #FFFFFF;
        border-radius: 21px;
        font-weight: 400;
        font-size: 16px;
        color: #0094FF;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: auto;
        margin-top: 15px;

        .imgs {
            width: 25%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: right;
        }

        .title {
            width: 70%;
            display: flex;
            align-items: center;
            padding-left: 10px;
            box-sizing: border-box;
        }

        .van-image {
            width: 16px;
            height: 16px;
        }
    }

    .flexd {
        display: flex;
        align-items: center;
    }

    .titles {
        font-weight: 500;
        font-size: 16px;
        color: #1A1B1C;
        margin: 15px 0 10px 15px;
    }

    .conent_pre {
        width: 100%;
        padding: 15px;
        box-sizing: border-box;
        background-color: #fff;
        margin-top: 10px;

        .conent_pre_header {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .conent_pre_img {
                width: 90px;
                height: 90px;

                .van-image {
                    width: 90px;
                    height: 90px;

                    :deep(.van-image__img) {
                        border-radius: 5px !important;
                    }
                }
            }

            .conent_pre_des {
                width: calc(100% - 90px);
                height: 90px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-wrap: wrap;
                padding-left: 10px;
                align-content: space-around;

                .contnt_title {
                    width: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .contnt_styleName {
                        font-weight: 400;
                        font-size: 14px;
                        color: #1A1B1C;
                        width: 150px;
                        height: 20px;
                        white-space: nowrap;
                        /* 确保文本在一行内显示 */
                        overflow: hidden;
                        /* 隐藏溢出的内容 */
                        text-overflow: ellipsis;
                    }

                    .contnt_status {
                        width: 67px;
                        height: 26px;
                        background: #EBF4FF;
                        border-radius: 2px;
                        font-weight: 400;
                        font-size: 14px;
                        color: #0094FF;
                        text-align: center;
                        line-height: 26px;
                    }

                }

                .contnt_mechanism {
                    width: 100%;
                    font-weight: 400;
                    font-size: 12px;
                    color: #B8BECA;
                    white-space: nowrap;
                    /* 确保文本在一行内显示 */
                    overflow: hidden;
                    /* 隐藏溢出的内容 */
                    text-overflow: ellipsis;
                }

                .contnt_bottom {
                    width: 100%;
                    height: 20px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .price {
                        font-weight: 500;
                        font-size: 14px;
                        color: #FC2540;
                    }

                    .commission {
                        font-weight: 500;
                        font-size: 14px;
                        color: #FC2540;
                    }

                    .coreName {
                        font-weight: 400;
                        font-size: 12px;
                        color: #0094FF;
                    }
                }
            }
        }

        .product_detail_title-content-info {
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .product_detail_title-content-info-name {
                font-weight: 400;
                font-size: 14px;
                color: #1a1b1c;
                line-height: 14px;
                width: 100px;
            }

            .colors {
                color: #0094FF !important;
            }

            .product_detail_title-content-info-content {
                flex: 1;
                min-width: 0;
                font-weight: 400;
                font-size: 14px;
                color: #b8beca;
                line-height: 14px;
                margin-left: auto;
                display: flex;
                justify-content: flex-end;
                word-break: break-all;
            }

            .contents {
                width: 200px;
                font-weight: 400;
                font-size: 14px;
            }

            .buttons {
                width: 67px;
                height: 26px;
                background: #fff;
                border-radius: 2px;
                font-weight: 400;
                font-size: 14px;
                color: #FC2540;
                text-align: center;
                line-height: 26px;
                border: 1px solid #FC2540;
            }
        }

    }

    .conent {
        flex: 1;
        min-height: 0;
        width: 100%;
        overflow: auto;
        box-sizing: border-box;
    }

    .conputed_bottom {
        width: 100%;
        background: #FFFFFF;
        box-shadow: 0px -3px 4px 0px rgba(212, 217, 223, 0.3);
        box-sizing: border-box;
        padding: 0 15px;

        .retained {
            width: 100%;
            border-bottom: 1px solid #ececec;
            display: flex;
            flex-flow: column;
            box-sizing: border-box;
            padding: 10px 0 5px;

            .label {
                width: 100%;
                font-weight: 400;
                font-size: 14px;
                color: #1a1b1c;
                margin-bottom: 10px;
            }

            .value {
                width: 100%;
                display: flex;
                flex-wrap: wrap;

                .imgList {
                    position: relative;
                    margin-right: 5px;

                    .loading_pic {
                        width: 90px;
                        height: 90px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }

                    :deep(.van-icon) {
                        position: absolute;
                        top: 0;
                        z-index: 100;
                        right: 0;
                        font-size: 10px;
                        height: 15px;
                        width: 15px;
                        background-color: #000;
                        border-bottom-left-radius: 16px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                    }

                    :deep(.van-icon-cross:before) {
                        margin: 0 0 1px 2px;
                    }
                }

                :deep(.van-image__img) {
                    width: 60px;
                    height: 60px;
                }
            }
        }

        .conputed_bottom_total {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 70px;
        }

        .conputed_bottom_left {
            display: flex;
            align-items: center;

            .van-image {
                width: 40px;
                height: 40px;
                font-weight: 400;
                font-size: 14px;
                color: #1A1B1C;
                margin-right: 10px;

            }

            .span {
                font-weight: 500;
                font-size: 21px;
                color: #0094FF;
            }
        }

        .button {
            width: 120px;
            height: 40px;
            background: #0094FF;
            border-radius: 23px;
            text-align: center;
            line-height: 40px;
            font-weight: 400;
            font-size: 14px;
            color: #FFFFFF;
        }
    }
}
</style>